package com.tj.view.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/11/10 0010.
 *
 * 自动滚动的文字(公告)
 *
 * 原理是：在textview的基础上，不断的改变文字的位置，来给人滚动的感觉
 *
 * 注意点:
 * 1: view的宽度和高度，文字的宽度和高度
 * 2:起点位置在view中间，然后离开view，重新设定起点在view右边开始,然后循环
 * 3:点击可以停止滚动
 *
 */
public class AutoScrollTextView extends TextView implements View.OnClickListener {

    public final static String TAG = AutoScrollTextView.class.getSimpleName();
    public boolean isStarting = false;//是否开始滚动
    private float textLength = 0f;//文本长度
    private float viewWidth = 0f;
    private float step = 0f;//文字的横坐标
    private float y = 0f;//文字的纵坐标
    private float temp_view_plus_text_length = 0.0f;//用于计算的临时变量
    private float temp_view_plus_two_text_length = 0.0f;//用于计算的临时变量
    private Paint paint = null;//绘图样式
    private String text = "";//文本内容

    private float textHeight;
    private float viewHeight;

    public AutoScrollTextView(Context context) {
        super(context);
        initView();
    }

    public AutoScrollTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }


    private void initView() {
        setOnClickListener(this);
    }

    /**
     * 各个宽度，高度的计算，起点的位置等
     * @param windowManager
     */
    public void init(WindowManager windowManager) {
        paint = getPaint();
        text = getText().toString();
        //文字的宽度测量
        textLength = paint.measureText(text);
        //文字的高度测量
        textHeight = paint.descent()+paint.ascent();
        //view的宽度测量
//        viewWidth = getWidth();
//        if (viewWidth == 0) {
//            if (windowManager != null) {
//                Display display = windowManager.getDefaultDisplay();
//                viewWidth = display.getWidth();
//            }
//        }
        //开始位置从view的尾端
//        temp_view_plus_text_length = viewWidth + textLength;
//        temp_view_plus_two_text_length = viewWidth + textLength * 2;

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //view的宽度和高度测量(在viewTree里测量才准确)
                viewWidth = getWidth();
                viewHeight = getHeight();

                step = textLength;

                //中间的位置 (用view高度的一半减去文字高度的一半)
                y = viewHeight / 2 - textHeight/ 2;

                //起点位置: view的中间
                temp_view_plus_text_length = (viewWidth/2 - textLength/2)+ textLength;

                //从起点到文字全部滚动出view显示的长度
                temp_view_plus_two_text_length = (viewWidth/2 - textLength/2) + textLength*2;

                //移除之前已经注册的全局布局回调函数
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        ss.step = step;
        ss.isStarting = isStarting;

        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        step = ss.step;
        isStarting = ss.isStarting;

    }

    public void startScroll() {
        isStarting = true;
        //重新绘制，调用ondraw
        invalidate();
    }

    public void stopScroll() {
        isStarting = false;
        invalidate();
    }

    /**
     * 滚动的核心--- 不停的绘制textview显示的位置
     * @param canvas
     */
    @Override
    public void onDraw(Canvas canvas) {
        //第二个参数表示文字显示的开始位置在textview的尾端
        //第三个参数表示文字开始时的Y轴的位置，这里是设置为中间显示
        canvas.drawText(text, temp_view_plus_text_length - step, y, paint);

        if (!isStarting) {
            return;
        }

        //1.5为文字滚动速度。
        step += 1.5;

        //当超出滚动的文字全部超出时，"重置",重新开始从左到右
        if (step > temp_view_plus_two_text_length){
            step = textLength;
            //新的起点位置: view的尾端
            temp_view_plus_text_length = viewWidth + textLength;
            //新的需要滚动的长度: view 和文字的长度的两倍
            temp_view_plus_two_text_length = viewWidth + textLength * 2;
        }
        invalidate();
    }

    @Override
    public void onClick(View v) {
        //点击可以开始，和暂停滚动
        if (isStarting){
            stopScroll();
        }else{
            startScroll();
        }
    }

    public static class SavedState extends BaseSavedState {
        public static final Parcelable.Creator<SavedState> CREATOR
                = new Parcelable.Creator<SavedState>() {

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }
        };
        public boolean isStarting = false;
        public float step = 0.0f;

        SavedState(Parcelable superState) {
            super(superState);
        }


        private SavedState(Parcel in) {
            super(in);
            boolean[] b = null;
            in.readBooleanArray(b);
            if (b != null && b.length > 0)
                isStarting = b[0];
            step = in.readFloat();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeBooleanArray(new boolean[]{isStarting});
            out.writeFloat(step);
        }
    }

}
